<?php
// +----------------------------------------------------------------------
// | 知识星球[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 abcblockchain.io
// +----------------------------------------------------------------------
// | 后台管理使用了HisiPHP
// +----------------------------------------------------------------------
// | Author: abcblockchain.io
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;
use think\Db;
use app\common\model\Message as msgModel;
use app\common\model\Users as usersModel;

/**
 * 评论模型
 * @package app\common\model
 */
class Comments extends Model
{
    // 定义时间戳字段名
    protected $createTime = 'ctime';
    protected $updateTime = false;

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;


    /**
     * 发表评论
     * @param array $data
     * @author jyx
     * @return stirng|array
     */
    public function createComments($data = [], $login = true)
    {
        $map = [];
        $map['target_user'] = $data['target_user'];
        $map['user_id'] = $data['user_id'];
        $map['body'] = $data['body'];
        $map['commentable_id'] = $data['commentable_id'];
        $map['reply_user'] = isset($data['reply_user']) ? $data['reply_user'] : 0;

        $res = $this->validate('Comments.create')->isUpdate(false)->save($map);
        if (!$res) {
            return false;
        } else {
            Db::name('group_posts')->where('id', $data['commentable_id'])->setInc('comments_count');
            $postInfo = Db::name('group_posts')->where('id', $data['commentable_id'])->field('group_id')->find();
            $userModel = new usersModel();
            $userInfo = $userModel->usersInfo($data['user_id']);
            $msgModel = new msgModel();
            $msgModel->createMsg($data['target_user'], 2, $data['user_id'], $userInfo['nick'], $postInfo['group_id'],$data['commentable_id']);
            return true;
        }
    }

    //关联用户表
    public function hasCommentUser()
    {
        return $this->hasOne('Users', 'id', 'user_id');
    }

    //关联用户表
    public function hasPost(){
        return $this->hasOne('group_posts', 'id', 'commentable_id');
    }

    //关联用户表
    public function hasReply(){
        return $this->hasOne('Users', 'id', 'reply_user');
    }

    /**
     * 获取帖子评论
     * @author
     * @param $postId
     */
    public function getReply($postId, $startNo = 0, $limit = 6){
        $map['c.commentable_id'] = $postId;
        $map['c.commentable_type'] = 1;
        $map['c.disabled'] = 1;
        $startNo = $startNo * $limit;
        $commentList = $this->alias('c')->join('users u', 'c.user_id=u.id')->join('users reu','c.reply_user=reu.id','LEFT')->where($map)->field('c.user_id,c.body,c.images,c.reply_user,c.ctime,u.nick,reu.nick as renick,u.avatar')->limit($startNo,$limit)->select();
        return $commentList;
    }

}
